package com.jumper.property.comparer.core.logger;


import com.jumper.property.comparer.core.DiffUtil;
import com.jumper.property.comparer.core.context.ActionContext;
import com.jumper.property.comparer.core.context.Context;
import com.jumper.property.comparer.core.context.DataChangeContext;
import com.jumper.property.comparer.core.result.DiffResult;
import com.jumper.property.comparer.core.result.Log;
import com.jumper.property.comparer.core.enums.LogType;
import com.jumper.property.comparer.core.support.DataLogger;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DataLoggerImpl implements DataLogger {

    @Override
    public List<Log> log(Context context, LogType type) {
        assert type != null;
        assert context != null;
        switch (type) {
            case Action:
                return logAction((ActionContext) context);
            case DataChange:
                return logDataChange((DataChangeContext) context);
        }
        throw new IllegalArgumentException("暂不支持此类型");
    }

    /**
     * 记录数据变化日志
     */
    private List<Log> logDataChange(DataChangeContext context) {
        DiffResult diff = DiffUtil.resolve(context.getCls(), context.getBeforeData(), context.getAfterData());
        return diff.isHasDiff() ? convert(diff.getDiffs(), context) : new ArrayList<>();
    }

    /**
     * 日志类型转换
     */
    private List<Log> convert(String diffs, DataChangeContext context) {
        return Stream.of(diffs).map(e -> {
            Log log = new Log();
            log.setDataKey(context.getOptDataKey());
            log.setOptTime(LocalDateTime.now());
            log.setAction(context.getOptName());
            log.setLogValue(e);
            log.setUser(context.getUser());
            return log;
        }).collect(Collectors.toList());
    }

    /**
     * 操作日志记录
     */
    private List<Log> logAction(ActionContext context) {
        Log log = new Log();
        log.setDataKey(context.getOptDataKey());
        log.setOptTime(LocalDateTime.now());
        log.setAction(context.getOptName());
        log.setLogValue(context.getLogValue());
        log.setUser(context.getUser());
        return Stream.of(log).collect(Collectors.toList());
    }
}
